import java.util.Scanner;

public class ElectronicCalendar {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 获取用户输入的年份和月份
        System.out.print("请输入年份：");
        int year = scanner.nextInt();
        System.out.print("请输入月份：");
        int month = scanner.nextInt();

        // 显示日历
        displayCalendar(year, month);

        scanner.close();
    }

    public static void displayCalendar(int year, int month) {
        // 显示标题
        System.out.println("\n=============================");
        System.out.println("         " + year + "年 " + month + "月");
        System.out.println("=============================");
        System.out.println("日 一 二 三 四 五 六");

        // 计算该月第一天是星期几
        int startDay = getStartDay(year, month);

        // 计算该月的天数
        int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);

        // 打印空格直到第一天开始
        for (int i = 0; i < startDay; i++) {
            System.out.print("   ");
        }

        // 打印日历
        for (int i = 1; i <= numberOfDaysInMonth; i++) {
            System.out.printf("%2d ", i);
            if ((i + startDay) % 7 == 0 || i == numberOfDaysInMonth) {
                System.out.println();
            }
        }
    }

    public static int getStartDay(int year, int month) {
        final int BASE_YEAR = 1900;
        final int BASE_START_DAY_FOR_JAN_1_1900 = 1; // 星期一

        int totalDays = getTotalDays(year, month);
        return (totalDays + BASE_START_DAY_FOR_JAN_1_1900) % 7;
    }

    public static int getTotalDays(int year, int month) {
        final int[] DAYS_IN_MONTH = {
                31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
        };

        int totalDays = 0;
        for (int i = 1900; i < year; i++) {
            if (isLeapYear(i)) {
                totalDays += 366;
            } else {
                totalDays += 365;
            }
        }

        for (int i = 0; i < month - 1; i++) {
            totalDays += DAYS_IN_MONTH[i];
        }

        if (month > 2 && isLeapYear(year)) {
            totalDays++;
        }

        return totalDays;
    }

    public static int getNumberOfDaysInMonth(int year, int month) {
        final int[] DAYS_IN_MONTH = {
                31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
        };

        if (month == 2 && isLeapYear(year)) {
            return 29;
        } else {
            return DAYS_IN_MONTH[month - 1];
        }
    }

    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
}
